#include "EditorSceneOutlineAbilityModel.h"

#include "Window/EditorWindowGroupModel.h"
#include "Pages/Scene/EditorScenePageModel.h"

#include "Scene/Scene.h"
#include "Scene/SceneNode.h"

void REditorSceneOutlineAbilityModel::FirstTimeInitializeObject()
{
    REditorWindowGroupModel::Get()->OnCurrentPageChanged.BindScript(
        this
        ,&REditorSceneOutlineAbilityModel::OnFocusedPageChanged);

    OnFocusedPageChanged(REditorWindowGroupModel::Get()->GetFocusedPage());
}

void REditorSceneOutlineAbilityModel::OnFocusedPageChanged(TSharedObjectPtr<REditorPageModel> InPage)
{
    if(InPage)
    {
        if(InPage->IsA<REditorScenePageModel>())
        {
            REditorScenePageModelPtr ScenePage=InPage;
            Scene=ScenePage->Scene;
        
            ExpandedNodes.Resize(1);
            ExpandedNodes[0]=Scene;

            OnSceneChanged.ExecuteIfBound();
            return;
        }
    }

    if(Scene)
    {
        Scene=nullptr;
        ExpandedNodes.Clear();

        OnSceneChanged.ExecuteIfBound();
    }
}

TSharedObjectPtr<RScene> REditorSceneOutlineAbilityModel::GetScene() const
{
    return Scene;
}

bool REditorSceneOutlineAbilityModel::IsNodeExpanded(TSharedObjectPtr<RObject> Node) const
{
    return ExpandedNodes.Contains(Node);
}

void REditorSceneOutlineAbilityModel::FocusNode(TSharedObjectPtr<RObject> Node)
{
    FocusedNode=Node;

    if(!FocusedNode->IsA<RSceneNode>())
    {
        return;
    }

    auto FocusedPage=REditorWindowGroupModel::Get()->GetFocusedPage();
    REditorScenePageModelPtr ScenePage=FocusedPage;
    if(!Node && !ScenePage)
    {
        return;
    }
    assert(ScenePage);
    ScenePage->SetSelectedNode(Node);
}
